import 'dart:convert';

import 'package:hello_flutter/domain/AppData.dart';
import 'package:hello_flutter/domain/WorkItem.dart';
import 'package:hello_flutter/util/PATClient.dart';
import 'package:intl/intl.dart';

class TFSClient {
  PATClient patClient;

  AppData appData;

  TFSClient(this.appData) : this.patClient = PATClient(appData.userPAT);

  Future<String> generateReporter() async {
    var wks = await query();
    var i = 1;
    final nf = new NumberFormat("##00");
    var r = wks.map((e) => '${nf.format(i++)}. ${e.title}').toList().join('\r\n');
    appData.reporter = r;
    print("周报: \n$r");

    return r;
  }

  Future<List<WorkItem>> query() async {
    var sql = Uri.encodeComponent(
        'SELECT [System.Id],[System.WorkItemType],[System.Title],[System.AssignedTo],[System.State],[System.Tags],[System.CreatedBy],[System.CreatedDate],[System.ChangedBy],[System.ChangedDate],[Microsoft.VSTS.Common.ClosedDate] '
        'FROM WorkItems WHERE '
        '[System.TeamProject] = @project '
        'AND [System.AssignedTo] = @me '
        'AND [Microsoft.VSTS.Common.StateChangeDate] >= @today - ${appData.days} '
        'ORDER BY [System.CreatedDate] ASC');
    var resp = await PATClient(appData.userPAT)
        .post(
            '${appData.collectionUrl}/${appData.projectName}/_api/_wit/query?__v=5',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: 'wiql=$sql')
        .timeout(Duration(seconds: 5));

    if (resp.statusCode != 200) throw '查询工作项失败 status ${resp.statusCode}';
    var jsonMap = jsonDecode(resp.body);
    var payload = jsonMap['payload'];
    var columns = payload['columns'];
    var rows = payload['rows'];
    return (rows as List).map((e) => WorkItem(e[3])).toList();
  }
}
